package com.atguigu.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/2 10:01
 */
public class Flink01_WC_Batch {
    public static void main(String[] args) throws Exception {
        // 1.获取执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // 2.读取数据
        DataSource<String> inputDS = env.readTextFile("input/word.txt");

        // 3.处理数据
        // 3.1 压平：切分\转成二元组(word,1)
        FlatMapOperator<String, Tuple2<String, Long>> wordAndOneDS = inputDS.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                // 切分
                String[] words = value.split(" ");
                for (String word : words) {
                    // 使用采集器，往下游发送
                    out.collect(Tuple2.of(word, 1L));
                }
            }
        });
        // 3.2 分组:按照 word分组
        UnsortedGrouping<Tuple2<String, Long>> wordAndOneGroup = wordAndOneDS.groupBy(0);
        // 3.3 组内求和
        AggregateOperator<Tuple2<String, Long>> result = wordAndOneGroup.sum(1);

        // 4.输出（打印）
        result.print();

        // 启动(DataSetAPI批处理 不用启动)
    }


}
